package com.taobao.pamirs.schedule.zk.thread;

import com.taobao.pamirs.schedule.strategy.TbScheduleManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 * @version 1.0
 * @author jiangyixin
 * @date 2021/2/5 下午2:45
 */
public class InitialThread extends Thread {
	private final static transient Logger log = LoggerFactory.getLogger(InitialThread.class);
	TbScheduleManagerFactory factory;
	boolean isStop = false;
	
	public InitialThread(TbScheduleManagerFactory aFactory) {
		this.factory = aFactory;
	}
	
	public void stopThread() {
		this.isStop = true;
	}
	
	@Override
	public void run() {
		this.factory.getLock().lock();
		try {
			int count = 0;
			while (!factory.getZkManager().checkZookeeperState()) {
				count = count + 1;
				if (count % 50 == 0) {
					String errorMessage = "Zookeeper connecting ......" +
							factory.getZkManager().getConnectStr()
							+ " spendTime:" + count * 20
							+ "(ms)";
					factory.setErrorMessage(errorMessage);
					log.error(factory.getErrorMessage());
				}
				Thread.sleep(20);
				if (this.isStop) {
					return;
				}
			}
			factory.initialData();
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
		} finally {
			factory.getLock().unlock();
		}
		
	}
}
